<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="订单编号:" prop="queryOrederId">
        <el-input v-model="queryParams.queryOrederId" placeholder="根据订单编号搜索" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>


      <el-form-item label="操作人qq号:" prop="queryOperatorQQ">
        <el-input v-model="queryParams.queryOperatorQQ" placeholder="根据qq号搜索" clearable style="width: 120px"
          @keyup.enter="handleQuery" />
      </el-form-item>



      <el-form-item label="操作日期:">
        <el-date-picker style="width: 220px" v-model="dateRange" value-format="YYYY-MM-DD" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @keyup.enter="handleQuery" />
      </el-form-item>

     <el-form-item label="操作类型:" prop="queryOperationType">
        <el-select :style="{ width: '140px' }" v-model="queryParams.queryOperationType" placeholder="请选择" clearable>
          <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

     <el-form-item label="只看审核操作:" prop="queryApply">
        <el-select :style="{ width: '140px' }" v-model="queryParams.queryApply" placeholder="请选择" clearable>
          <el-option   label="是" :value="1" />
           <el-option    label="否" :value="2"  />
        </el-select>

       
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>




    </el-form>

    <el-row :gutter="10" class="mb8">


      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60" />

      <el-table-column label="订单编号" align="center" prop="order_id" width="150" :show-overflow-tooltip="true">

      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="goodsName" width="200" :show-overflow-tooltip="true" />
      <el-table-column label="操作人qq号" align="center" prop="operator" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="操作人角色" align="center" prop="operatorRoles" width="150" :show-overflow-tooltip="true" />


      <el-table-column label="操作日期" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, "{y}-{m}-{d} {hh}:{mm}") }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作类型" align="center" prop="operation_type" width="130">
        <template #default="scope">
          <dict-tag :options="typeList" :value="scope.row.operation_type" />
        </template>
      </el-table-column>

      <el-table-column label="操作描述" align="left" prop="operation_desc" width="200" :show-overflow-tooltip="true" />

      <el-table-column label="操作" align="center" width="200" :fixed="desk" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleRead(scope.row)">查看差异</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />


    <!-- 添加或修改公告对话框 -->
    <el-dialog title="差异对比" v-model="open1" width="1000px" append-to-body>
      <CodeDiff :old-string="oldJson" :new-string="newJson" output-format="side-by-side" />

    </el-dialog>


  </div>
</template>

<script setup name="Order">

import { CodeDiff } from 'v-code-diff'

import {
  listOrder,
  addOrder,
  addOrderList,
  applyOrder,
  applyOrderWx,
  updateOrder,
  updateOrderZhuan,
  deleteOrder,
  downExcelOrder,
  downExcelFile,
} from "@/api/business/order";



import { listGoods } from "@/api/business/goods";
import { listUser, listAllUser } from "@/api/business/user";

import { listOrderLogs } from "@/api/business/orderLogs";

import { useDebounceFn } from "@vueuse/core";
import useDesk from "@/hooks/useDesk";
import { logsEnums, orderStatusEnums, orderTypeEnums } from "@/utils/enums"
import { status } from "nprogress";

const { desk } = useDesk();
const { proxy } = getCurrentInstance();
// 图片上传地址
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadFile/file";
const uploadUrl1 =
  import.meta.env.VITE_APP_UPLOAD_API + "api/uploadFileEdit/file";
const uploadShowUrl = import.meta.env.VITE_APP_COS_API;

const imgSrc = ref("");
const pageList = ref([]);
const open = ref(false);
const open1 = ref(false);

const oldJson = ref('')
const newJson = ref('')


const dialogOpen1 = ref(false); // 导出表格
const dialogOpen2 = ref(false); // 导入表格


const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const painterList = ref([]); // 画师下拉框
const useOtherPlatformList = ref([
  { label: "是", value: "是" },
  { label: "否", value: "否" },
]);
// 是否赞助
const statusComList = ref([
  { label: "否", value: 1 },
  { label: "是", value: 2 },
]);
const approveList = ref([
  { label: "通过", value: 1 },
  { label: "不通过", value: 2 },
]);

const loadingGoods = ref(false);

const optionsPainterList = ref([]);
const optionsGoodsList = ref([]);

const optionsUser = ref([]); //  用户搜索
const loadingUser = ref(false);

const loadingSubmit = ref(false);
const loadingBtn = ref(false);
const fileList = ref([]);

const dateRange = ref([]);


// 赞助状态
const stutasList = ref([
  // 1标准单  2转让单  3待赠单  4已赠单'
  {
    label: "标准单",
    value: 1,
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "转让单",
    value: 2,
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "待赠单",
    value: 3,
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "已赠单",
    value: 4,
    elTagClass: "",
    elTagType: "success",
  },
]);
const data = reactive({
  typeList: logsEnums,
  statusList: orderStatusEnums,
  form: {},
  form1: {},
  dialogForm1: {
    goodsId: undefined,
    beginTime: undefined,
    end: undefined,
    painterId: undefined,
  }, // 导出弹出框选择
  dialogForm2: {
    goodsId: undefined,
  }, // 导出弹出框选择

  queryParams: {
    pageNum: 1,
    pageSize: 20,
    status: 2,
   
    queryOrederId: undefined,
    queryGoodsId: undefined,
    queryPainterQQ: undefined,
    queryUserName: undefined,
    queryTransferQQ: undefined,
    queryStartEndTime: undefined,
  },
  rules: {
    goodsId: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
    buyerQQ: [
      { required: true, message: "购买用户QQ不能为空", trigger: "change" },
    ],
    type: [
      { required: true, message: "订单类型不能为空", trigger: "change" },
    ],

  },
});

const { queryParams, form, dialogForm1,
  typeList,
  form1,
  statusList,
  dialogForm2, rules } =
  toRefs(data);


// 定义 key 映射关系
const keyMapping = {
  "id": "订单编号",
  "logs": "logs",
  "type": "订单类型",
  "wd_id": "wd_id",
  "origin": "订单来源",
  "status": "转让中",
  "buy_sum": "订单数量",
  "remarks": "备注",
  "buy_date": "购买时间",
  "buyer_qq": "购买人QQ号",
  "goods_id": "商品ID",
  "platform": "平台",
  "buy_price": "购买价格",
  "createdAt": "创建时间",
  "updatedAt": "更新时间",
  "sponsor_qq": "被赞人QQ",
  "transfer_qq": "转让人QQ",
  "sponsor_date": "赞助时间",
  "transfer_date": "转让时间",
};

// 转化Key
function renameJsonKeys(jsonObj, keyMapping) {
  // 使用 Object.keys 获取 JSON 对象的键，然后用 reduce 方法创建新对象
  return Object.keys(jsonObj).reduce((acc, key) => {
    // 如果原始 key 在映射对象中存在，使用映射后的新 key，否则保留原 key
    const newKey = keyMapping[key] || key;
    acc[newKey] = jsonObj[key];
    return acc;
  }, {});
}

/** 查询公告列表 */
function getList() {
  loading.value = true;

  listOrderLogs(proxy.addDateRangeZL(queryParams.value, dateRange.value)).then(
    (response) => {
      pageList.value = response.data.rows.map((item) => {
        // 把订单状态转换成中文
        if (item.before_content.status) {
          const oldValRes_status = orderStatusEnums.find(item1 => item1.value === item.before_content.status);
          item.before_content.status = oldValRes_status.label
        }
        if (item.after_content.status) {
          const newValRes_status = orderStatusEnums.find(item1 => item1.value === item.after_content.status);
          item.after_content.status = newValRes_status.label
        }

        // 订单类型
        if (item.before_content.type) {
          const oldValRes_type = orderTypeEnums.find(item1 => item1.value === item.before_content.type);
          item.before_content.type = oldValRes_type.label
        }
        if (item.after_content.type) {
          const newValRes_type = orderTypeEnums.find(item1 => item1.value === item.after_content.type);
          item.after_content.type = newValRes_type.label
        }



        item.before_content = renameJsonKeys(item.before_content, keyMapping);

        item.after_content = renameJsonKeys(item.after_content, keyMapping);
        let oldVal = JSON.stringify(item.before_content, null, 4)
        let newVal = JSON.stringify(item.after_content, null, 4)
        return {
          ...item,
          oldVal,
          newVal
        }
      });

      total.value = response.data.count;
      loading.value = false;
    }
  );
}
function handleRead(val) {
  open1.value = true;

  oldJson.value = val.oldVal
  newJson.value = val.newVal



}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 取消按钮 */
function cancel1() {
  open.value = false;
  reset1();
}
/** 新增表单重置 */
function reset1() {
  form1.value = {

  };

  proxy.resetForm("noticeRef1");
}

/** 新增表单重置 */
function reset() {
  form.value = {

  };
  data.rules = {
    goodsId: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
    buyerQQ: [
      { required: true, message: "购买用户QQ不能为空", trigger: "change" },
    ],
    type: [
      { required: true, message: "订单类型不能为空", trigger: "change" },
    ],
  };
  proxy.resetForm("noticeRef");
}



/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}

/** 取消按钮 */
function dialogCancel1() {
  dialogOpen1.value = false;
  dialogReset1();
}
/** 取消按钮 */
function dialogCancel2() {
  dialogOpen2.value = false;
  dialogReset2();
}

function handleExport() {
  dialogReset1();
  dialogOpen1.value = true;
  title.value = "导出表格";
}
/** 导入表格 */
function handleUpload() {
  dialogReset2();
  dialogOpen2.value = true;
  title.value = "导入表格";
}

/** 表单重置 */
function dialogReset1() {
  proxy.resetForm("orderRef1");
}

/** 表单重置 */
function dialogReset2() {
  proxy.resetForm("orderRef2");
  fileList.value = [];
}




/**修改按钮操作 */
function handleUpdate(row) {
  reset();

  if (!row.id) {
    let arr = pageList.value.filter((item) => {
      return item.id == ids.value;
    });
    form.value = {
      ...arr[0],
      name: arr[0].goodsName,
    };
  } else {
    form.value = {
      ...row
    };

    optionsGoodsList.value = [
      {
        label: row.goodsName,
        value: row.goodsId,
      },
    ];

  }
  title.value = "修改";
  open.value = true;
}

// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      loadingSubmit.value = true;
      if (form.value.id != undefined) {
        if (form.value.takeoutStatusOld == 1 && form.value.takeoutStatus == 2) {
          updateOrderZhuan(form.value)
            .then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              loadingSubmit.value = false;
              open.value = false;

              getList();
            })
            .catch(() => {
              loadingSubmit.value = false;
            });
        } else {
          updateOrder(form.value)
            .then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              loadingSubmit.value = false;
              open.value = false;

              getList();
            })
            .catch(() => {
              loadingSubmit.value = false;
            });
        }
      } else {

        addOrder(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            loadingSubmit.value = false;
            open.value = false;

            getList();
          })
          .catch(() => {
            loadingSubmit.value = false;
          });

      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }
  let arrList = pageList.value.filter((item) => {
    return;
  });
  proxy.$modal
    .confirm('是否确认删除编号为"' + deleteId + '"的数据项？')
    .then(function () {
      return deleteOrder({ id: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}
/** 商品名远程搜索 */
function remoteMethodGoods(query) {
  if (query) {
    loadingGoods.value = true;
    let queryParams = {
      pageNum: 1,
      pageSize: 50,
      queryGoodsName: query,
    };
    listGoods(queryParams).then((response) => {
      optionsGoodsList.value = response.data.rows.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });

      loadingGoods.value = false;
    });
  } else {
    optionsGoodsList.value = [];
  }
}
/** 商品远程搜索 */
function remoteMethod1(query) {
  if (query) {
    loadingGoods.value = true;
    let queryParams = {
      pageNum: 1,
      pageSize: 50,
      queryGoodsName: query,
    };
    listGoods(queryParams).then((response) => {
      optionsGoodsList.value = response.data.rows.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });

      loadingGoods.value = false;
    });
  } else {
    optionsPainterList.value = [];
  }
}

/** 画师远程搜索 */
function remoteMethod2(query) {
  if (query) {
    loadingGoods.value = true;
    let queryParams = {
      pageNum: 1,
      pageSize: 50,
      queryNickname: query,
      type: 3
    };
    listUser(queryParams).then((response) => {
      optionsPainterList.value = response.data.rows.map((item) => {
        return {
          label: item.nickname,
          value: item.id,
        };
      });

      loadingGoods.value = false;
    });
  } else {
    optionsPainterList.value = [];
  }
}



/** 导出 */
function submitExport() {
  const dataForm = dialogForm1.value;
  let fileName = "订单";
  if (dataForm.queryDate) {
    fileName = fileName + dataForm.queryDate + ".xlsx";
  } else {
    fileName = fileName + ".xlsx";
  }
  if (dataForm.queryDate) {
    let Time = dataForm.queryDate;
    let y = new Date(Time).getFullYear(); //获取年份
    let m = new Date(Time).getMonth() + 1; //获取月份
    let begin = Time + "-01";
    let end = Time + "-" + new Date(y, m, 0).getDate(); //获取当月最后一日
    dataForm.beginTime = begin;
    dataForm.endTime = end;
  } else {
    dataForm.beginTime = undefined;
    dataForm.endTime = undefined;
  }
  loadingBtn.value = true;
  downExcelOrder(dataForm).then((response) => {
    loadingBtn.value = false;

    downFile(response, fileName);
  });
}
// 可以将此方法封装
function downFile(content, filename) {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement("a");
  eleLink.download = filename;
  eleLink.style.display = "none";
  // 字符内容转变成blob地址
  var blob = new Blob([content]);
  eleLink.href = URL.createObjectURL(blob);
  document.body.appendChild(eleLink);
  // 触发点击
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
  proxy.$modal.msgSuccess("操作成功");
}
// dialogForm1.painterId
/** 商品名远程搜索 */
function remoteMethodGoods1(query) {

  remoteMethod1(query)
}

/** 上传用 */
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 2) {
    proxy.$modal.msgError("  文件大于 2MB!");
    return false;
  }
  return true;
}
function onSuccessImg(response) {
  if (response.code == 200) {
    proxy.$modal.msgSuccess(response.msg);
    getList();
  } else {
    proxy.$modal.msgError(response.msg);
  }
}

/** 下载标准模板 */
function submitUploadFileDemo(response) {
  let fileName = "无言订单标准模板2025.xlsx";
  loadingBtn.value = true;
  downExcelFile({}).then((response) => {
    loadingBtn.value = false;
    downFile(response, fileName);
  });
}

/** 判断是否可以转让 */
function handleShowTakeOut(row) {
  let goodsStatus = row.goodsStatus; // 商品转让状态
  let createTime = row.createTime; // 购买时间
  let takeoutStatus = row.takeoutStatus; // 订单的转让状态

  if (goodsStatus == 2) {
    return {
      code: 2,
      txt: "禁止转让：商品禁止转让",
    };
  }
  if (takeoutStatus == 2) {
    return {
      code: 3,
      txt: "禁止转让：订单已经被转让过了",
    };
  }
  let nowDate = new Date().getTime();
  let lastDate = new Date(createTime).getTime();
  let day90 = 90 * 24 * 60 * 60 * 1000;
  let day365 = 365 * 24 * 60 * 60 * 1000;

  if (nowDate - lastDate <= day90 || nowDate - lastDate > day365) {
    return {
      code: 4,
      txt: "禁止转让：购买日期不在3个月至1年之内",
    };
  } else {
    return {
      code: 1,
      txt: "可以转让",
    };
  }
}
/** 查询画师列表 */
function getPainterList() {
  listAllUser({
    type: 3
  }).then((response) => {
    painterList.value = response.data.map((item) => {
      return {
        label: item.nickname || '-空-',
        value: item.id,
        elTagType: 'default' //不需要tag标签
      };
    });
  });
}

/**审核按钮操作 */
function handleApprove(row) {

  form1.value.id = row.id;
  form1.value.buyer_qq = row.buyerQQ;
  form1.value.transfer_qq = row.transferQQ;
  open1.value = true;
  title.value = "审批";
}
// 防抖操作
const debouncedFn1 = useDebounceFn(
  () => {
    submitForm1();
  },
  1000,
  { maxWait: 3000 }
);

/** 提交按钮 */
function submitForm1() {
  if (!form1.value.id) {
    proxy.$modal.msgSuccess("错误");
  }
  proxy.$refs["noticeRef1"].validate((valid) => {
    if (valid) {
      loadingSubmit.value = true;
      let sendData = {}
      if (form1.value.approve == 1) {
        sendData = {
          status: 12,
          id: form1.value.id,
          type: 2,
        }
      } else {

        sendData = {
          status: 10,
          id: form1.value.id,
          buyer_qq: form1.value.transfer_qq,
          type: 1,
          transfer_date: undefined,
          transfer_qq: ''
        }
      }
      applyOrderWx(sendData)
        .then((response) => {
          proxy.$modal.msgSuccess("操作成功");
          loadingSubmit.value = false;
          open1.value = false;

          getList();
        })
        .catch(() => {
          loadingSubmit.value = false;
        });

    }
  });
}


watch(
  () => data.dialogForm1.painterId,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      goodsHttp(); // 重新搜索
      data.dialogForm1.goodsId = undefined;
    }
  },
  { deep: true }
);

getList();

getPainterList(); // 画师列表
</script>
<style lang="scss" scoped>
.goods-name {
  color: rgb(0, 119, 255);
  cursor: pointer;
}

.green {
  color: #2eacf5;
}

.red {
  color: red;
}
</style>
